'use strict';

const Controller = require('egg').Controller;

class AwardController extends Controller {
  async create() {
    const ctx = this.ctx;
    try {
      ctx.validate({
        name: 'string',
        type: 'string',
        total_inventory: 'int',
      });

      const data = ctx.request.body;

      // 免息券编号去重
      if (data.type === '4') {
        ctx.validate({
          coupon_code: 'string'
        }, data);
        const coupon = await this.ctx.app.model.Award.findOne({coupon_code: data.coupon_code});
        if (coupon) {
          throw new Error('优惠券编号重复');
        }
      }

      const campaign = new this.ctx.app.model.Award(Object.assign(data, {
        remaining_inventory: data.total_inventory,
        creator: {
          operator_id: this.ctx.v._id,
          realname: this.ctx.v.realname,
        },
      }));
      await campaign.save();

      this.ctx.body = {
        code: 0,
        msg: '保存成功',
      };
    } catch (e) {
      ctx.body = {
        code: 1,
        msg: `${e.message}`,
      };
      ctx.logger.error(e);
    }
  }

  async chooseList() {
    const ctx = this.ctx;
    try {
      const body = ctx.request.body;
      const data = {
        name: body.name || '',
        type: body.type || '',
      };
      const result = await ctx.service.award.chooseList(data);
      ctx.body = {
        code: 0,
        data: result,
      };
    } catch (e) {
      ctx.body = {
        code: 1,
        msg: `${e.message}`,
      };
      ctx.logger.error(e);
    }
  }

  async list() {
    const ctx = this.ctx;
    try {
      const body = ctx.request.query;
      const data = {
        name: body.name || '',
        type: body.type || '',
        pageIndex: +body.pageIndex,
        pageSize: +body.pageSize,
      };
      ctx.validate({
        pageIndex: {type: 'int', min: '1'},
        pageSize: {type: 'int', min: '1'},
      }, data);
      const result = await ctx.service.award.list(data);
      ctx.body = {
        code: 0,
        data: result,
      };
    } catch (e) {
      ctx.body = {
        code: 1,
        msg: `${e.message}`,
      };
      ctx.logger.error(e);
    }
  }

  async get() {
    const ctx = this.ctx;
    try {
      this.ctx.validate({
        id: 'string',
      }, ctx.params);

      const award = await ctx.app.model.Award.findOne({
        _id: ctx.params.id,
      });

      ctx.body = {
        code: 0,
        data: award,
        msg: '查询成功',
      };
    } catch (e) {
      ctx.body = {
        code: 1,
        msg: `${e.message}`,
      };
      ctx.logger.error(e);
    }
  }

  async delete() {
    const ctx = this.ctx;
    try {
      ctx.validate({
        id: 'string',
      }, ctx.params);

      const campaignAwards = await ctx.app.model.Campaign.findOne({"awards": {"$elemMatch": {"_id": ctx.app.__mongoose.Types.ObjectId(this.ctx.params.id)}}});
      if (campaignAwards) {
        throw new Error('该奖品已被使用，不允许删除');
      }

      await ctx.app.model.Award.update({
        _id: this.ctx.params.id,
      }, {
        deleted: true,
      });

      ctx.body = {
        code: 0,
        msg: '删除成功',
      };
    } catch (e) {
      ctx.body = {
        code: 1,
        msg: `${e.message}`,
      };
      ctx.logger.error(e);
    }
  }

  async update() {
    const ctx = this.ctx;
    try {
      ctx.validate({
        id: 'string',
      }, ctx.params);

      const awardInfo = await ctx.model.Award.findById(ctx.params.id);
      if (!awardInfo) {
        throw new Error('没有这个奖品');
      }
      const inc = ctx.request.body.total_inventory - awardInfo.total_inventory;
      if (awardInfo.remaining_inventory + inc < 0) {
        throw new Error(`奖品库存为${awardInfo.remaining_inventory},不能减少到小于0`);
      }

      await ctx.app.model.Award.update({
        _id: this.ctx.params.id,
      }, {
        $set: {update_time: new Date()},
        $inc: {remaining_inventory: inc, total_inventory: inc},
      });

      ctx.body = {
        code: 0,
        msg: '更新成功',
      };
    } catch (e) {
      ctx.body = {
        code: 1,
        msg: `${e.message}`,
      };
      ctx.logger.error(e);
    }
  }
}

module.exports = AwardController;
